package com.haixiaoke.saas.messageCenter.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.haixiaoke.saas.common.constant.Constants;
import com.haixiaoke.saas.common.constant.MessageConstants;
import com.haixiaoke.saas.common.exception.ServiceException;
import com.haixiaoke.saas.common.utils.ChannelNameUtil;
import com.haixiaoke.saas.common.utils.DateUtils;
import com.haixiaoke.saas.department.domain.Tenant;
import com.haixiaoke.saas.department.service.ITenantService;
import com.haixiaoke.saas.listeners.DingTalkMessageListener;
import com.haixiaoke.saas.listeners.WechatTalkMessageListener;
import com.haixiaoke.saas.messageCenter.domain.MessageChannel;
import com.haixiaoke.saas.messageCenter.domain.OrdinaryMessage;
import com.haixiaoke.saas.messageCenter.mapper.MessageChannelMapper;
import com.haixiaoke.saas.messageCenter.service.IMessageChannelService;
import com.haixiaoke.saas.messageCenter.service.IOrdinaryMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 机构消息渠道信息Service业务层处理
 *
 * @author xiaolong
 * @date 2024-11-08
 */
@Service
public class MessageChannelServiceImpl implements IMessageChannelService {
    @Autowired
    private MessageChannelMapper messageChannelMapper;
    @Autowired
    private ITenantService tenantService;
    @Autowired
    private IOrdinaryMessageService ordinaryMessageService;

    /**
     * 查询机构消息渠道信息
     *
     * @param messageChannelId 机构消息渠道信息主键
     * @return 机构消息渠道信息
     */
    @Override
    public MessageChannel selectMessageChannelByMessageChannelId(Long messageChannelId) {
        return messageChannelMapper.selectMessageChannelByMessageChannelId(messageChannelId);
    }

    /**
     * 查询机构消息渠道信息列表
     *
     * @param messageChannel 机构消息渠道信息
     * @return 机构消息渠道信息
     */
    @Override
    public List<MessageChannel> selectMessageChannelList(MessageChannel messageChannel) {
        return messageChannelMapper.selectMessageChannelList(messageChannel);
    }

    /**
     * 新增机构消息渠道信息
     *
     * @param messageChannel 机构消息渠道信息
     * @return 结果
     */
    @Override
    public int insertMessageChannel(MessageChannel messageChannel) {
        if (Constants.SHUT.equals(messageChannel.getWechatState()) && Constants.SHUT.equals(messageChannel.getDingState())) {
            throw new ServiceException("请至少选择一种消息渠道");
        }
        Tenant tenant = tenantService.selectDepartmentByDepId(messageChannel.getTenantId());
        if (ObjectUtil.isEmpty(tenant)) {
            throw new ServiceException("机构不存在");
        }
        MessageChannel channel = messageChannelMapper.selectMessageChannelByTenantId(messageChannel.getTenantId());
        if (ObjectUtil.isNotEmpty(channel)) {
            throw new ServiceException("该机构已配置消息渠道");
        }

        // 组合消息渠道名称
        packageMessageChannel(messageChannel);

        // 校验配置信息
        if (Constants.OPEN.equals(messageChannel.getWechatState())) {
            validateWechatConfig(messageChannel);
        }
        if (Constants.OPEN.equals(messageChannel.getDingState())) {
            validateDingTalkConfig(messageChannel);
        }

        messageChannel.setTenantName(tenant.getTenantName());
        messageChannel.setCreateTime(DateUtils.getNowDate());
        return messageChannelMapper.insertMessageChannel(messageChannel);
    }

    private static void packageMessageChannel(MessageChannel messageChannel) {
        Map<String, String> states = new HashMap<>();
        states.put(MessageConstants.PUSH_CHANNEL_ENTERPRISE_WECHAT, messageChannel.getWechatState());
        states.put(MessageConstants.PUSH_CHANNEL_DING_TALK, messageChannel.getDingState());
        String channelName = ChannelNameUtil.getCombinedChannelNames(states);
        messageChannel.setMessageChannelName(channelName);
    }

    private static void validateDingTalkConfig(MessageChannel messageChannel) {
        if (StrUtil.isEmpty(messageChannel.getDingAgentId())) {
            throw new ServiceException("钉钉配置信息有误，请检查");
        }
        try {
            DingTalkMessageListener.verifyInfo(messageChannel.getDingAppKey(), messageChannel.getDingAppSecret());
        } catch (Exception e) {
            throw new ServiceException("钉钉配置信息有误，请检查");
        }
    }

    private static void validateWechatConfig(MessageChannel messageChannel) {
        if (StrUtil.isEmpty(messageChannel.getWechatAgentId())) {
            throw new ServiceException("企业微信配置信息有误，请检查");
        }
        WechatTalkMessageListener.verifyInfo(messageChannel.getWechatCorpid(), messageChannel.getWechatSecret());
    }

    /**
     * 修改机构消息渠道信息
     *
     * @param messageChannel 机构消息渠道信息
     * @return 结果
     */
    @Override
    public int updateMessageChannel(MessageChannel messageChannel) {
        Tenant tenant = tenantService.selectDepByDepId(messageChannel.getTenantId());
        if (ObjectUtil.isEmpty(tenant)) {
            throw new ServiceException("机构不存在");
        }


        // 组合消息渠道名称
        packageMessageChannel(messageChannel);

        // 校验配置信息
        if (Constants.OPEN.equals(messageChannel.getWechatState())) {
            validateWechatConfig(messageChannel);
        }
        if (Constants.OPEN.equals(messageChannel.getDingState())) {
            validateDingTalkConfig(messageChannel);
        }

        messageChannel.setTenantName(tenant.getTenantName());
        messageChannel.setUpdateTime(DateUtils.getNowDate());
        return messageChannelMapper.updateMessageChannel(messageChannel);
    }

    /**
     * 批量删除机构消息渠道信息
     *
     * @param messageChannelIds 需要删除的机构消息渠道信息主键
     * @return 结果
     */
    @Override
    public int deleteMessageChannelByMessageChannelIds(Long[] messageChannelIds) {
        return messageChannelMapper.deleteMessageChannelByMessageChannelIds(messageChannelIds);
    }

    /**
     * 删除机构消息渠道信息信息
     *
     * @param messageChannelId 机构消息渠道信息主键
     * @return 结果
     */
    @Override
    public int deleteMessageChannelByMessageChannelId(Long messageChannelId) {
        MessageChannel messageChannel = messageChannelMapper.selectMessageChannelByMessageChannelId(messageChannelId);
        if (ObjectUtil.isEmpty(messageChannel)) {
            throw new ServiceException("消息渠道不存在");
        }

        List<OrdinaryMessage> ordinaryMessageList = ordinaryMessageService.selectOrdinaryMessageByTenantId(messageChannel.getTenantId());
        if (CollectionUtil.isNotEmpty(ordinaryMessageList)) {
            throw new ServiceException("该渠道存在消息模板引用，请先删除消息模板");
        }

        messageChannel.setDelFlag(Constants.DEL_FLAG_NO);
        return messageChannelMapper.updateMessageChannel(messageChannel);
    }

    @Override
    public String verifyMessageChannel(MessageChannel messageChannel) {
        // 校验消息渠道配置
        List<OrdinaryMessage> ordinaryMessageList = ordinaryMessageService.selectOrdinaryMessageByTenantIdAndPushChannel(messageChannel.getTenantId(), messageChannel.getPushChannel());
        if (CollectionUtil.isNotEmpty(ordinaryMessageList)) {
            throw new ServiceException("该渠道存在消息模板引用，请先删除消息模板");
        }
        return "成功";
    }

    @Override
    public MessageChannel selectMessageChannelByTenantId(String tenantId) {
        return messageChannelMapper.selectMessageChannelByTenantId(tenantId);
    }

    @Override
    public MessageChannel getInfoByTenantId(String tenantId) {
        MessageChannel messageChannel = messageChannelMapper.selectMessageChannelByTenantId(tenantId);
        if (ObjectUtil.isEmpty(messageChannel)) {
            messageChannel = new MessageChannel();
            messageChannel.setTenantId(tenantId);
            messageChannel.setWechatState(Constants.SHUT);
            messageChannel.setDingState(Constants.SHUT);
        }
        return messageChannel;
    }
}
